package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    private Socket socket;

    public Client2(){
        try {
            System.out.println("正在启动客户端....");
            socket = new Socket("localhost",8090);
            System.out.println("客户端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        /*
            给服务端写东西
         */
        try {
             /*
            读取每一个客户端包括本客户端给服务器写的消息
         */
            Runnable runnable = new ServerHandler();
            Thread t = new Thread(runnable);
            t.start();

            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(),"UTF-8"
                            )
                    )
            ,true);



            Scanner scan = new Scanner(System.in);
            System.out.println("输入你想对服务器说的话:  ");
            while(true){
               String line = scan.nextLine();
               if ("exit".equals(line)){
                   break;
               }
                pw.println(line);

               //这里写一次，才能读一次服务端发过来的消息，不满足需求，我们的需求是，每个连上服务端的客户端写的东西都能被服务端写给
                //每一个客户端，所有读服务端的消息的过程是和写同时并发进行的，所有我们需要开线程执行这些代码

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client2 client2 = new Client2();
        client2.start();
    }

    private class ServerHandler implements Runnable{
        public void run(){
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String severMessage;
                while ((severMessage = br.readLine()) != null){
                    System.out.println(severMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
